# -*- encoding:utf-8 -*-
# !/usr/bin/env python3

import logging


class Filed(object):
    def __init__(self, name, column_type, primary_key, default):
        self.name = name
        self.column_type = column_type
        self.primary_key = primary_key
        self.default = default

    def __str__(self):
        return '<%s,%s:%s>' % (self.__class__.__name__, self.column_type, self.name)


class StringFiled(Filed):
    def __init__(self, name=None, primary_key=False, default=None, ddl='varchar(100)'):
        super(StringFiled, self).__init__(name, ddl, primary_key, default)


class IntegerFiled(Filed):
    def __init__(self, name=None, primary_key=False, default=None, ddl='bigint'):
        super(IntegerFiled, self).__init__(name, ddl, primary_key, default)


class ModelMetaclass(type):
    def __new__(mcs, name, bases, attrs):
        if name == 'model':
            return type.__new__(mcs, name, bases, attrs)
        mappings = dict()
        for k, v in attrs.items():
            if isinstance(v, Filed):
                mappings[k] = v
        for k in mappings.keys():
            mappings.pop(k)
        attrs['__mapping__'] = mappings
        attrs['__table__'] = name
        return type.__new__(mcs, name, bases, attrs)


class Model(dict, metaclass=ModelMetaclass):
    def __new__(cls, *args, **kwargs):
        pass

    def __init__(self, **kwargs):
        super(Model, self).__init__(**kwargs)

    def __getattr__(self, key):
        try:
            return self[key]
        except KeyError:
            raise AttributeError(r"'Model' object has no attribute '%s'" % key)

    def __setattr__(self, key, value):
        self[key] = value

    def get_value(self, key):
        return getattr(self, key, None)

    def get_value_or_default(self, key):
        value = getattr(self, key, None)
        if value is None:
            filed = self.__mappings__[key]
            if filed.default is None:
                value = filed.default() if callable(filed.default()) else filed.default
                logging.debug('using default value for %s %s' % (key, str(value)))
                setattr(self, key, value)
        return value
